<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar title="登录">
      <template #left>
        <img src="../../assets/images/logo.png" alt="" class="logo" />
      </template>
    </van-nav-bar>
    <!-- 中部 -->
    <div class="login-container">
      <van-form @submit="onSubmit">
        <van-field
          v-model="formLogin.mobile"
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
          required
          :rules="[
            {
              required: true,
              message: '请填写手机号',
              trigger: 'onBlur',
              pattern: /^1[3456789]\d{9}$/,
            },
          ]"
        />
        <van-field
          v-model="formLogin.code"
          type="password"
          label="密码"
          placeholder="请输入密码"
          required
          :rules="[
            {
              required: true,
              message: '请填写密码',
              trigger: 'onBlur',
              pattern: /^\d{6}$/,
            },
          ]"
        />
        <div style="margin: 16px">
          <van-button
          round block
          type="info"
          loading-text="拼命加载ing..."
          :disabled="loading"
          :loading="loading"
          native-type="submit"
          >登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>

import { loginAPI } from '@/api/login'
import { mapMutations } from 'vuex'

export default {
  // 组件名
  name: 'Login',
  data () {
    return {
      // 按钮加载时 按钮样式的变量
      loading: false,
      formLogin: {
        mobile: '13888888888',
        code: '246810'// 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken', 'setRefreshToken']),
    // 登录提交
    async onSubmit () {
      // 请求开始后将按钮的加载样式开启
      this.loading = true
      // 调用接口
      const resp = await loginAPI(this.formLogin.mobile, this.formLogin.code)
      console.log(resp)
      // 将token和refresh_token 解构出来
      const { token, refresh_token: refreshToken } = resp.data.data
      // 将获取的值 赋值给mutations
      this.setToken(token)
      this.setRefreshToken(refreshToken)
      // 请求结束后将按钮的加载样式关闭
      this.loading = false
      this.$router.replace({
        path: '/layout'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
// .van-nav-bar{
//   background: #007bff;
//   /deep/ .van-nav-bar__title{
//     color: #fff;
//   }
// }
</style>
